<script setup>
import adminApi from '@/api/adminApi';
import {reactive, ref} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus'
import router from "@/router";

const admins = ref([]);

// 分页信息
const pageInfo = reactive({
  page: 1,
  limit: 10,
  total: 0,
})

// 获取管理员列表
loadAdmins();

// 页码和页面大小更新
function loadAdmins() {
  adminApi.search(pageInfo).then(result => {
    admins.value = result.data.records;
    pageInfo.total = result.data.total;
  });
}

// 添加的相关操作
const addVisible = ref(false);
const addAdmin = ref({roles: []});

function showAdd() {
  addVisible.value = true;    // 显示添加窗口
}

function handleAdd() {
  adminApi.add(addAdmin.value).then(result => {
    if (result.code == 200) {
      ElMessage({message: '管理员创建成功！', type: 'success'})
      addVisible.value = false;
      addAdmin.value = {roles: []};
    } else {
      ElMessage.error(result.data);
    }
    // 刷新表格数据
    loadAdmins();
  });
}

// 编辑的操作
const editVisible = ref(false);
const editAdmin = ref({});

const loginAdmin = ref({
  name: "未登录",
});
getLoginAdmin();
function getLoginAdmin() {
  adminApi.getLoginAdmin().then(result => {
    if (result.code == 200) {
      loginAdmin.value.name = result.data;
      //router.push('/charts')
    } else {
      router.push('/login')
    }
  });
}

function handleDelete(row) {
  ElMessageBox.confirm('此操作将永久删除该管理员, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    adminApi.remove(row.id).then(result => {
      if (result.code == 200) {
        ElMessage({message: '注销成功！', type: 'success'})
        if (loginAdmin.value.name==result.data){
          localStorage.removeItem('token');
          router.push('/login')
        }
        //清除token
        loadAdmins();
      } else {
        ElMessage.error(result.msg);
      }
    })
  })
}

function handleEdit() {
  adminApi.edit(editAdmin.value).then(result => {
    if (result.code == 200) {
      ElMessage({message: '编辑管理员成功！', type: 'success'})
      editVisible.value = false;
    } else {
      ElMessage.error(result.data);
    }
    // 刷新表格数据
    loadAdmins();
  });
}

function onSearch() {
  pageInfo.page = 1;
  loadAdmins();
}

//格式化密码
function formatPassword(row, column, cellValue, index) {
  if (cellValue) {
    return '*'.repeat(6);
  }
  return '';
}

// 密码确认相关
const passwordConfirmVisible = ref(false);
const currentAdminPassword = ref('');
const pendingEditAdmin = ref({}); // 临时存储待编辑的管理员信息

// 修改 showEdit 方法
function showEdit(row) {
  // 先保存要编辑的管理员信息
  pendingEditAdmin.value = JSON.parse(JSON.stringify(row));
  pendingEditAdmin.value.password = "";

  // 显示密码确认对话框
  passwordConfirmVisible.value = true;
  currentAdminPassword.value = '';
}

// 确认密码方法
function confirmPassword() {
  // 这里应该调用后端API验证当前登录管理员的密码
  // 假设有一个API用于验证当前登录用户的密码
  adminApi.verifyPassword({ password: currentAdminPassword.value ,id: pendingEditAdmin.value.id}).then(result => {
    if (result.code == 200) {
      // 密码验证成功，显示编辑对话框
      passwordConfirmVisible.value = false;
      currentAdminPassword.value = '';

      // 将待编辑的管理员信息赋值给编辑表单
      editAdmin.value = pendingEditAdmin.value;
      pendingEditAdmin.value = {};

      // 显示编辑对话框
      editVisible.value = true;
    } else {
      ElMessage.error('密码错误，请重新输入');
    }
  }).catch(() => {
    ElMessage.error('密码验证失败');
  });
}
//定义校验规则
const rules=ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
  ],
  name: [
      { required: true, message: '请输入姓名', trigger: 'blur' },
      { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { min: 11, max: 11, message: '长度为11位', trigger: 'blur' }
  ]
})
</script>

<template>
  <div class="content">
    <el-form :model="pageInfo" :inline="true">
      <el-form-item label="名字" :label-width="60">
        <el-input v-model="pageInfo.name" placeholder="请输入管理员名字"/>
      </el-form-item>
      <el-form-item label="电话" :label-width="60">
        <el-input v-model="pageInfo.phone" placeholder="请输入管理员电话"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">
          <el-icon>
            <Search></Search>
          </el-icon>
        </el-button>
      </el-form-item>
    </el-form>
    <div class="bar">
      <el-button type="success" @click="showAdd">创建管理员</el-button>
    </div>
    <el-table :data="admins" :stripe="true" :border="true" style="width: 100%">
      <el-table-column prop="id" label="ID" width="180"/>
      <el-table-column prop="name" label="姓名"/>
      <el-table-column prop="username" label="用户名" width="180"/>
      <!--      展示一个隐藏的密码-->
      <el-table-column prop="password" label="密码" width="180" :formatter="formatPassword"/>
      <el-table-column prop="phone" label="手机号" width="180"/>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" type="success"
                     @click="showEdit(scope.row)">编辑
          </el-button>
          <el-button size="small" type="danger"
                     @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination class="page" v-model:current-page="pageInfo.page" v-model:page-size="pageInfo.limit"
                   :total="pageInfo.total" :page-sizes="[10, 20, 50, 100]" :background="true"
                   layout="total, sizes, prev, pager, next, jumper" @change="loadAdmins"/>
  </div>

  <!-- 添加的弹窗 -->
  <el-dialog v-model="addVisible" title="创建新管理员" width="500">
    <el-form :model="addAdmin" :rules="rules">
      <el-form-item label="姓名" :label-width="90" prop="name">
        <el-input v-model="addAdmin.name" autocomplete="off" style="width: 300px;"/>
      </el-form-item>
      <el-form-item label="用户名" :label-width="90" prop="username">
        <el-input v-model="addAdmin.username" autocomplete="off" style="width: 300px;"/>
      </el-form-item>
      <el-form-item label="电话" :label-width="90" prop="phone">
        <el-input v-model="addAdmin.phone" autocomplete="off" style="width: 300px;"/>
      </el-form-item>
      <el-form-item label="密码" :label-width="90" prop="password">
        <el-input v-model="addAdmin.password" autocomplete="off" show-password style="width: 300px;"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAdd">
          创建
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 编辑的弹窗 -->
  <el-dialog v-model="editVisible" title="编辑管理员" width="500">
    <el-form :model="editAdmin" :rules="rules">
      <el-form-item label="姓名" :label-width="90" prop="name">
        <el-input v-model="editAdmin.name" autocomplete="off" disabled/>
      </el-form-item>
      <el-form-item label="电话" :label-width="90" prop="phone">
        <el-input v-model="editAdmin.phone" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="用户名" :label-width="90" prop="username">
        <el-input v-model="editAdmin.username" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="密码" :label-width="90" prop="password">
        <el-input v-model="editAdmin.password" autocomplete="off" show-password/>
      </el-form-item>

    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEdit">
          编辑
        </el-button>
      </div>
    </template>
  </el-dialog>

<!--  密码确认弹窗-->
<el-dialog v-model="passwordConfirmVisible" title="确认密码" width="500">
  <el-form>
    <el-form-item label="请输入您的密码" :label-width="120">
      <el-input v-model="currentAdminPassword" autocomplete="off" show-password style="width: 300px;"/>
    </el-form-item>
  </el-form>
  <template #footer>
    <div class="dialog-footer">
      <el-button @click="passwordConfirmVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmPassword">
        确认
      </el-button>
    </div>
  </template>
</el-dialog>


</template>

<style>

</style>